public class Test {
    public static void main(String[] args) throws Exception {
        BookShelf shelf = new BookShelf(3);
        shelf.add("Clean Code");
        shelf.add("Design Patterns");
        shelf.add("Refactoring");

        Iterator<String> it = shelf.createIterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}
// 迭代器 = “遍历接口标准化”；
// 集合管存储，迭代器管顺序访问，解耦又通用，Java 的 Iterator、C# 的 IEnumerator 都是它
/* ---------- 抽象层 ---------- */
interface Iterator<T> {
    boolean hasNext();

    T next();
}

interface Aggregate<T> {
    Iterator<T> createIterator();
}

/* ---------- 具体集合 ---------- */
class BookShelf implements Aggregate<String> {
    private final String[] books;
    private int size;

    BookShelf(int cap) {
        books = new String[cap];
    }

    void add(String book) {
        books[size++] = book;
    }

    public Iterator<String> createIterator() {
        return new BookIterator(this);
    }

    String get(int idx) {
        return books[idx];
    }

    int length() {
        return size;
    }
}

/* ---------- 具体迭代器 ---------- */
class BookIterator implements Iterator<String> {
    private final BookShelf shelf;
    private int index = 0;

    BookIterator(BookShelf shelf) {
        this.shelf = shelf;
    }

    public boolean hasNext() {
        return index < shelf.length();
    }

    public String next() {
        return shelf.get(index++);
    }
}